package top.letscode.adclicker.driver;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.io.TemporaryFilesystem;
import org.openqa.selenium.support.ui.ExpectedConditions;

import top.letscode.adclicker.executor.ExecutorThreadLocal;
import top.letscode.adclicker.util.Utils;

public class WebDriverHelper {

  public static void checkAlertPresent(WebDriver webDriver) {
    try {
      while (true) {
        webDriver.switchTo().alert().accept();
        Utils.sleepQuietly(2);
      }
    } catch (Exception e) {

    }
    try {
      // 如果一直有弹窗，一直点击确定
      List<String> handleList = new ArrayList<String>(webDriver.getWindowHandles());
      if (handleList.size() > 1) {
        for (int i = 1; i < handleList.size(); i++) {
          webDriver.switchTo().window(handleList.get(i));
          webDriver.close();
        }

        webDriver.switchTo().window(handleList.get(0));
      }

    } catch (Exception e) {

    }
  }

  public static void close(WebDriver webDriver) {
    if (webDriver != null) {
      try {
        checkAlertPresent(webDriver);
        TemporaryFilesystem tempFS = TemporaryFilesystem.getDefaultTmpFS();
        tempFS.deleteTemporaryFiles();
        webDriver.manage().deleteAllCookies();
        webDriver.quit();
        webDriver = null;
      } catch (UnhandledAlertException e) {// 可能弹出框没关闭，先关闭弹出框再关闭webDriver
        try {
          webDriver.switchTo().alert().accept();
          webDriver.quit();
          webDriver = null;
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      } catch (Exception e) {// ignore

      } finally {
        if (webDriver != null) {
          try {
            webDriver.quit();
          } catch (Exception e) {

          }
        }
      }
    }
  }

  public static WebElement findElement(By by) {
    return ExecutorThreadLocal.get().getWebDriverWait()
        .until(ExpectedConditions.presenceOfElementLocated(by));
  }

  public static List<WebElement> findElements(By by) {
    return ExecutorThreadLocal.get().getWebDriverWait()
        .until(ExpectedConditions.presenceOfAllElementsLocatedBy(by));
  }
}
